import matplotlib
matplotlib.use('TkAgg')
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import os
import matplotlib.pyplot as plt
from moviepy.editor import ImageSequenceClip
from moviepy.editor import VideoFileClip

clip =VideoFileClip("D:/1.mp4")

caaa=clip.audio
audio_path = "D:/output.wav"  # 你提取的音频文件
y, sr = librosa.load(audio_path, sr=None)  # y 是采样点数据，sr 是采样率

# ======================
# 2. 参数设置
# ======================
meizhen = 0.1  # 每帧代表的时间长度（秒），比如 0.1 秒
frame_duration = meizhen
num_bars = 100  # 你要显示的白色小竖条数量（类似频谱条/波形条）

window_size = int(frame_duration * sr)  # 每帧包含多少个采样点
num_frames = int(len(y) / window_size)  # 总帧数

output_video_path = "D:/a.mp4"  # 输出视频路径
temp_frame_dir = "a"
os.makedirs(temp_frame_dir, exist_ok=True)

# ======================
# 3. 按时间分帧，每帧取 num_bars 个采样点，作为条的高度
# ======================
for frame_idx in range(num_frames):
    start_sample = frame_idx * window_size
    end_sample = start_sample + window_size

    if end_sample > len(y):
        end_sample = len(y)

    frame_samples = y[start_sample:end_sample]  # 当前帧的采样点数据

    # 如果该帧的采样点数量少于 num_bars，补零或截断
    if len(frame_samples) < num_bars:
        bar_heights = list(np.abs(frame_samples)) + [0.0] * (num_bars - len(frame_samples))
    else:
        bar_heights = list(np.abs(frame_samples[:num_bars]))  # 全部取正值，全部在上方显示

    # ======================
    # 4. 画 50 个白色小竖条
    # ======================
    plt.figure(figsize=(12, 2), facecolor='black')
    bars = plt.bar(range(num_bars), bar_heights, width=0.8, color='white', bottom=0)
    plt.ylim(-1.0, 1.0)  # 音频振幅范围通常在 [-1, 1]，可以根据需要调整
    plt.xlim(-1, num_bars)
    plt.axis('off')  # 不显示坐标轴
    plt.tight_layout(pad=0)
    plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

    # 保存当前帧
    frame_filename = f"{temp_frame_dir}/frame_{frame_idx:04d}.png"
    plt.savefig(frame_filename, facecolor='black', bbox_inches='tight', pad_inches=0)
    plt.close()

# ======================
# 5. 合成所有帧为 MP4 视频
# ======================
frame_files = sorted([f"{temp_frame_dir}/frame_{i:04d}.png" for i in range(num_frames)])
fps = int(1.0 / frame_duration)  # 比如 0.1秒一帧 => 10fps

clip = ImageSequenceClip(frame_files, fps=fps)
clip.write_videofile(output_video_path, codec='libx264', fps=fps)

# ======================
# 6. 清理临时文件
# ======================
import shutil
shutil.rmtree(temp_frame_dir)

print(f"✅ 动态波形条视频已生成：{output_video_path}")
